import $ from 'jquery';

import './workflow.less';
import axios from 'axios';
import diagramXML from './diagram.dmn';

import DmnModeler from 'dmn-js/lib/Modeler';
import camundaModdleDescriptor from 'camunda-dmn-moddle';

import {
  DmnPropertiesPanelModule,
  DmnPropertiesProviderModule,
  CamundaPropertiesProviderModule
} from 'dmn-js-properties-panel';

import Keycloak from 'keycloak-js';

var token;

function initKeycloak() {
  const keycloak = new Keycloak();
  console.log('set keycloak');
  keycloak.init({onLoad: 'login-required'}).then(function(authenticated) {
    if (authenticated) {
      console.log(keycloak.token);
      token = keycloak.token;
    }
  }).catch(function() {
      alert('failed to initialize');
  });
}

var dmnModeler = new DmnModeler({
  drd: {
    propertiesPanel: {
      parent: '#js-properties-panel'
    },
    additionalModules: [
      DmnPropertiesPanelModule,
      DmnPropertiesProviderModule,
      CamundaPropertiesProviderModule
    ],
  },
  container: '#js-canvas',
  moddleExtensions: {
    camunda: camundaModdleDescriptor
  }
});

var container = $('#js-drop-zone');

$('body').on('load', initKeycloak());

// Deployment button
$('#js-deployment').on("click", async function(event){
  const { xml } = await dmnModeler.saveXML({ format: true });
  console.log(xml);
  const parser = new DOMParser();
  const xmldoc = parser.parseFromString(xml, "application/xml");
  const decision = xmldoc.getElementsByTagName('decision');
  const decision_name = decision[0].getAttribute('name');
  const decision_id = decision[0].getAttribute('id');
  const encode_data = encodeURIComponent(xml);
  const file = new File([xml], "diagram.dmn", {type: "text/plain"});
  //const { svg } = await dmnModeler.saveSVG();
  //const img_file = new File([svg], "diagram.svg", {type: "image/svg+xml"});
  const data = new FormData();
  data.append("deployment-name", decision_name);
  data.append("data", file);
  //data.append("diagram", img_file);
  axios.create({withCredentials: true}).post(
    'http://localhost/camunda/engine-rest/deployment/create', 
    data, 
    {headers: {'Content-Type':'multipart/form-data', 'Authorization':'Bearer '+token}}
    ).then(
      res=>{
        console.log('res=>', res);
        if (res.status==200) {
          alert("部署成功，点击链接查看:"+res.data.links[0].href);
        }
        console.log(res.status);
        console.log(res.data.links[0].href);
      }
    )
})

function registerFileDrop(container, callback) {

  function handleFileSelect(e) {
    e.stopPropagation();
    e.preventDefault();
    var files = e.dataTransfer.files;

    var file = files[0];

    var reader = new FileReader();

    reader.onload = function(e) {

      var xml = e.target.result;

      callback(xml);
    };

    reader.readAsText(file);
  }

  function handleDragOver(e) {
    e.stopPropagation();
    e.preventDefault();

    e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
  }

  container.get(0).addEventListener('dragover', handleDragOver, false);
  container.get(0).addEventListener('drop', handleFileSelect, false);
}


// file drag / drop ///////////////////////

// check file api availability
if (!window.FileList || !window.FileReader) {
  window.alert(
    'Looks like you use an older browser that does not support drag and drop. ' +
    'Try using Chrome, Firefox or the Internet Explorer > 10.');
} else {
  registerFileDrop(container, openDiagram);
  console.log("registered");
}


function createNewDiagram() {
  openDiagram(diagramXML);
}

async function openDiagram(dmnXML) {

  try {

    await dmnModeler.importXML(dmnXML);

    container
      .removeClass('with-error')
      .addClass('with-diagram');

  } catch (err) {

    container
      .removeClass('with-diagram')
      .addClass('with-error');

    container.find('.error pre').text(err.message);

    console.error(err);
  }
}

$(function() {
  // load external diagram file via AJAX and open it
  //$.get(diagramUrl, openDiagram, 'text');
  $('#js-create-diagram').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    createNewDiagram();
  });

  var downloadLink = $('#js-download-diagram');
  var downloadSvgLink = $('#js-download-svg');

  $('.buttons a').click(function(e) {
    if (!$(this).is('.active')) {
      e.preventDefault();
      e.stopPropagation();
    }
  });

  function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
      link.addClass('active').attr({
        'href': 'data:application/xml;charset=UTF-8,' + encodedData,
        'download': name
      });
      console.log("added");
    } else {
      link.removeClass('active');
    }
  }

  var exportArtifacts = debounce(async function() {
    try {

      const { svg } = await dmnModeler.saveSVG();

      setEncoded(downloadSvgLink, 'diagram.svg', svg);
    } catch (err) {

      console.error('Error happened saving svg: ', err);
      setEncoded(downloadSvgLink, 'diagram.svg', null);
    }

    try {

      const { xml } = await dmnModeler.saveXML({ format: true });
      setEncoded(downloadLink, 'diagram.dmn', xml);
    } catch (err) {

      console.error('Error happened saving XML: ', err);
      setEncoded(downloadLink, 'diagram.dmn', null);
    }
  }, 500);

  dmnModeler.on('views.changed', exportArtifacts);
});

function debounce(fn, timeout) {

  var timer;

  return function() {
    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(fn, timeout);
  };
}